package com.lc1993929.stomp.controller;

import com.lc1993929.stomp.entity.Message;
import com.lc1993929.stomp.entity.Response;
import com.sun.java.browser.plugin2.liveconnect.v1.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.SendTo;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.messaging.simp.annotation.SubscribeMapping;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * Created by LiuChang on 2019/2/15
 */
@Controller
@Slf4j
public class WebSocketController {
    @Autowired
    SimpMessagingTemplate template;

    /**
     * 浏览器发送请求通过@messageMapping 映射/welcome 这个地址。
     * 服务器端有消息时,会订阅@SendTo 中的路径的浏览器发送消息。
     *
     * @param message
     * @return
     * @throws Exception
     */
    @MessageMapping("/welcome")
    @SendTo("/topic/getResponse")
    public Response say(Message message) throws Exception {
        Thread.sleep(1000);
        return new Response("Welcome, " + message.getName() + "!");
    }


    @GetMapping("/test")
    @ResponseBody
    String test() {
        return "test";
    }

    @MessageMapping("/sendTest")
    @SendTo("/topic/subscribeTest")
    public Response sendDemo(Message message) {
        log.info("接收到了信息" + message.getName());
        return new Response("你发送的消息为:" + message.getName());
    }

    @SubscribeMapping("/subscribeTest")
    public Response sub() {
        log.info("XXX用户订阅了我。。。");
        return new Response("感谢你订阅了我。。。");
    }

    /**
     * 可以利用普通http request来主动推送广播消息
     *
     * @return
     */
    //@RequestMapping("/welcome")
    //@ResponseBody
    public String say02() {
        try {
            template.convertAndSend("/topic/getResponse", new Response("欢迎！"));
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return "success";
    }
}
